using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using XMas;





namespace XMasEditor
{
    public partial class frmEditorMain : Form
    {
        // Temp node for create conections
        private AnimationNode _DragAnimNodeSource;
        private int _iDragAnimItemSource;
        private AnimationControls.AnimNodeControl _DragControlAnimNodeSource;        
        private System.Drawing.Point _DragBeginPoint;
        private System.Drawing.Point _DragEndPoint;
        private System.Drawing.Point _MenuPoint;
        private System.Drawing.Point _MovePanelPoint;

        // Contextual item menu temporal
        private AnimControlData _MenuAnimDataSource;
        private int _iMenuNodeItemSource;              
                
        // Our system
        private AnimationSystemEditor _AnimationSystem;

        // Hack to avoid acideltal panel move
        private bool _DisableNextPanelMove;
        private bool _bWasMovingNode;
        private bool _bNeedToAskConfirmation;
        private bool _bBoxSelecting;

        // Selected nodes
        private List<AnimControlData> _SelectedNodes;



        public frmEditorMain(ContentManager ContentManager)
        {
            InitializeComponent();

            
            // Create new animation system
            _AnimationSystem = new AnimationSystemEditor(splitContainer1.Panel2, ContentManager);
            _SelectedNodes = new List<AnimControlData>();

            _iDragAnimItemSource = -1;
            _DragControlAnimNodeSource = null;
            _DragAnimNodeSource        = null;
            _AnimationSystem.OnCreateGraphicalControl += OnCreateGraphicalControl;
            
            _MenuAnimDataSource = null;
            _iMenuNodeItemSource = -1;
            _MovePanelPoint = new System.Drawing.Point();
            _bBoxSelecting = false;

            // Mouse wheel
            this.MouseWheel += OnMouseWheelMove;
            propertyGrid1.MouseWheel += OnMouseWheelMove;            
            RecreateAnimCreationContextMenu();   
        }


        #region XNA Form Hack

        public float GetAspectratio()
        {
            return ((float)splitContainer1.Panel2.Width / (float)splitContainer1.Panel2.Height);
        }

        public IntPtr PanelHandle
        {
            get
            {
                return this.splitContainer3.Panel1.IsHandleCreated ?
                       this.splitContainer3.Panel1.Handle : IntPtr.Zero;
            }
        }

        public void RefreshPanel()
        {
            splitContainer1.Panel2.Refresh();
        }

        #endregion


        #region Properties


        [Browsable(false)]
        public Model CurrentModel
        {
            get { return _AnimationSystem.CurrentModel; }
        }

        #endregion


        #region AnimationSystem Functions

        public void UpdateAnimationSystem(TimeSpan elapsedTime, bool bRelativeToCurrentTime, Matrix matrixRootTransform)
        {
            _AnimationSystem.XMAnimationSystem.Update(elapsedTime);
        }

        public Matrix[] GetAnimationSkinTransforms()
        {
            return _AnimationSystem.XMAnimationSystem.GetSkinTransforms();
        }

        public Matrix GetModelWorldTransform()
        {
            return _AnimationSystem.XMAnimationSystem.SkiningData.worldModelTransform;
        }

        #endregion


        #region Graph Panel Functions

        private void onPaintPanel(object sender, PaintEventArgs e)
        {
            // Drag and drop process
            if (_DragControlAnimNodeSource != null)
            {
                _AnimationSystem.DrawCurve(e.Graphics, _DragBeginPoint, _DragEndPoint, System.Drawing.Color.Black);
            }
            if (_AnimationSystem != null)
            {
                _AnimationSystem.DrawAllConections(e.Graphics);
                _AnimationSystem.DrawAnimationsTime();
            }

            // Draw selection box
            if (_bBoxSelecting)
                e.Graphics.DrawRectangle(Pens.Black, GetCorrectRectangle(_DragBeginPoint, _MovePanelPoint));
        }

        private void onPanelMouseMove(object sender, MouseEventArgs e)
        {
            // If we have dragsource and MouseMove event raised, means that the drag can finish, clear
            if (_DragControlAnimNodeSource != null)
            {
                _iDragAnimItemSource = -1;
                _DragAnimNodeSource = null;
                _DragControlAnimNodeSource = null;
            }
            else
            {
                if (!_bBoxSelecting)
                {
                    // Control scroll
                    if (e.Button == MouseButtons.Left && !_DisableNextPanelMove)
                    {
                        // Delta
                        System.Drawing.Point pAux = new System.Drawing.Point(e.X - _MovePanelPoint.X, e.Y - _MovePanelPoint.Y);
                        _AnimationSystem.TranslateControls(pAux);
                        //_bNeedToAskConfirmation = true;
                    }
                    _DisableNextPanelMove = false;
                }
            }
            _MovePanelPoint = e.Location;
        }

        private void onDragOver(object sender, DragEventArgs e)
        {
            // Conection on progress, show future conection
            if (_DragControlAnimNodeSource != null)
            {
                _DragEndPoint = splitContainer1.Panel2.PointToClient(new System.Drawing.Point(e.X, e.Y));
                splitContainer1.Panel2.Refresh();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void onContexMenuClosed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            _DisableNextPanelMove = true;
        }

        private void onFormClosing(object sender, FormClosingEventArgs e)
        {
            if (!AskForConfirmation())
                e.Cancel = true;
        }

        private void OnMouseWheelMove(Object sender, MouseEventArgs e)
        {
            if (e.Delta < 0)
                _AnimationSystem.ScaleControls(false);
            else if (e.Delta > 0)
                _AnimationSystem.ScaleControls(true);
        }

        # endregion


        #region Utils Functions

        private void ClearCachedNode()
        {
            propertyGrid1.SelectedObject = null;
            _SelectedNodes.Clear();
            _DragAnimNodeSource = null;
            _DragControlAnimNodeSource = null;
            _MenuAnimDataSource = null;
        }

        private void ClearSelectedNodes()
        {
            foreach (AnimControlData animData in _SelectedNodes)
            {
                animData.AnimControl.CaptionColor = System.Drawing.Color.Black;
                if (propertyGrid1.SelectedObject == animData.AnimNode)
                    propertyGrid1.SelectedObject = null;
            }
            _SelectedNodes.Clear();
        }

        private System.Drawing.Rectangle GetCorrectRectangle(System.Drawing.Point p1, System.Drawing.Point p2)
        {
            System.Drawing.Point locationRes = new System.Drawing.Point(p1.X, p1.Y);
            int width = p2.X - p1.X;
            int height = p2.Y - p1.Y;
            if (width < 0)
            {
                locationRes.X = p2.X;
                width = -width;
            }
            if (height < 0)
            {
                locationRes.Y = p2.Y;
                height = -height;
            }
            return new System.Drawing.Rectangle(locationRes, new System.Drawing.Size(width, height));
        }


        private bool AskForConfirmation()
        {
            bool bResult = !_bNeedToAskConfirmation;
            if (!bResult)
            {
                DialogResult result = MessageBox.Show("All changes will be lost. Are you sure?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                bResult = result == DialogResult.Yes;
            }
            return bResult;
        }

        private void RecreateAnimCreationContextMenu()
        {
            // Clear and ading initial
            contextMenuAddNodes.Items.Clear();
            ToolStripMenuItem NodesWithOutCategory = new ToolStripMenuItem("NoCategory");
            List<ToolStripMenuItem> NodesWithCategory = new List<ToolStripMenuItem>();

            // Delete list
            _AnimationSystem.m_AssemblyList.Clear();
            
            // Get the main asembly
            Assembly asm = Assembly.GetAssembly(typeof(AnimationNode));
            AddAssemblyToList(asm, NodesWithOutCategory, NodesWithCategory);

            // Get all dlls in directory and load assembly
            string strDirectory = "./Content/Nodes";
            foreach (string fileName in Directory.GetFiles(strDirectory, "*.dll"))
            {
                string strFullName = Path.GetFullPath(fileName);
                try
                {
                    asm = Assembly.LoadFile(strFullName);
                }
                catch (Exception e)
                {
                    asm = null;
                    Console.WriteLine("Error " + e.Message + " loading asembly " + strFullName);
                }                
                if (asm != null)
                    AddAssemblyToList(asm, NodesWithOutCategory, NodesWithCategory);
            }


            // Ading menus            
            NodesWithCategory.Sort(delegate(ToolStripMenuItem x, ToolStripMenuItem y) { return x.Text.CompareTo(y.Text); });
            foreach (ToolStripMenuItem itemMenu in NodesWithCategory)
                contextMenuAddNodes.Items.Add(itemMenu);

            // Without category (problems with for each)
            for (int i = 0; i < NodesWithOutCategory.DropDownItems.Count; i++)
                contextMenuAddNodes.Items.Add(NodesWithOutCategory.DropDownItems[i]);       
           
        }

        private void AddAssemblyToList(Assembly asm, ToolStripMenuItem NodesWithOutCategory, List<ToolStripMenuItem> NodesWithCategory)
        {
            Type[] allTypes = asm.GetTypes();
            foreach (Type type in allTypes)
            {
                // Only scan classes that arn't abstract    
                if (type.IsClass && !type.IsAbstract && (type.IsSubclassOf(typeof(AnimationNode))))
                {
                    // Create a temporal object to determine where to insert                    
                    ToolStripMenuItem DestinationMenu = null;
                    object obj = asm.CreateInstance(type.FullName);
                    AnimationNode AnimNode = (AnimationNode)obj;
                    if (AnimNode.CategoryName.Length == 0)
                        DestinationMenu = NodesWithOutCategory;
                    else
                    {
                        // Seach category menu or create new
                        foreach (ToolStripMenuItem itemMenu in NodesWithCategory)
                        {
                            if (itemMenu.Text == AnimNode.CategoryName)
                            {
                                DestinationMenu = itemMenu;
                                break;
                            }
                        }
                        if (DestinationMenu == null)
                        {
                            DestinationMenu = new ToolStripMenuItem(AnimNode.CategoryName);
                            NodesWithCategory.Add(DestinationMenu);
                        }
                    }

                    ToolStripMenuItem ItemStrip = new ToolStripMenuItem("Add " + type.Name);
                    ItemStrip.Tag = type.FullName;
                    ItemStrip.Click += addAnimNodeToolStripMenuItem_Click;

                    DestinationMenu.DropDownItems.Add(ItemStrip);
                }
            }   
          
            // Add to list
            _AnimationSystem.m_AssemblyList.Add(asm);
        }

        #endregion
        

        #region Properties Grid

        private void onChangeValue(object s, PropertyValueChangedEventArgs e)
        {            
            // Si tengo probelmas con los grid y lista ver
            // check http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1584929&SiteID=1
            AnimControlData editorNode = _AnimationSystem.GetAnimDataFromNode((AnimationNode)propertyGrid1.SelectedObject);
            if (editorNode != null)
                _AnimationSystem.RecreateControl(editorNode);

            //_bNeedToAskConfirmation = true;
        }

        #endregion


        # region AnimNode Delegates

        private void onClickAnimNode(AnimationControls.AnimNodeControl pSourceNode)
        {
            // Like caption
            OnAnimNodeClickCaption(pSourceNode, new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
            /*
            // Buscamos el sourcenod
            AnimControlData animData = _AnimationSystem.GetAnimDataFromControl(pSourceNode);
            if (animData != null && animData.AnimNode != null)
            {
                propertyGrid1.SelectedObject = animData.AnimNode;
                propertyGrid1.Refresh();
                pSourceNode.BringToFront();
            }
            */
        }

        private void OnAnimNodeMove(AnimationControls.AnimNodeControl pDestNode, System.Drawing.Point pDelta)
        {
            // Move all selected (only if the node that raise event is selected)
            AnimControlData animSource = _AnimationSystem.GetAnimDataFromControl(pDestNode);
            if (_SelectedNodes.Contains(animSource))
            {
                foreach (AnimControlData animData in _SelectedNodes)
                {
                    System.Drawing.Point vNewPos = new System.Drawing.Point(
                        animData.AnimControl.Location.X + pDelta.X, animData.AnimControl.Location.Y + pDelta.Y);
                    animData.AnimControl.Location = vNewPos;
                    animData.AnimControl.BringToFront();
                }
                _bWasMovingNode = true;
                splitContainer1.Panel2.Refresh();
                _bNeedToAskConfirmation = true;
            }
            else
            {
                System.Drawing.Point vNewPos = new System.Drawing.Point(
                        animSource.AnimControl.Location.X + pDelta.X, animSource.AnimControl.Location.Y + pDelta.Y);
                animSource.AnimControl.Location = vNewPos;
                animSource.AnimControl.BringToFront();                
                _bWasMovingNode = true;
                splitContainer1.Panel2.Refresh();
                _bNeedToAskConfirmation = true;
            }
        }
        
        private void OnBeginCreateConection(AnimationControls.AnimNodeControl pSourceNode, int iIdx)
        {
            _DragBeginPoint = pSourceNode.GetConectionIdxPosition(iIdx);
            _DragEndPoint   = _DragBeginPoint;
            AnimControlData pAnimData = _AnimationSystem.GetAnimDataFromControl(pSourceNode);
            if (pAnimData != null && pAnimData.AnimNode != null && iIdx >= 0 && iIdx < pAnimData.AnimNode.ItemList.Count)
            {
                _iDragAnimItemSource = iIdx;
                _DragAnimNodeSource = pAnimData.AnimNode;
                _DragControlAnimNodeSource = pSourceNode;
            }
        }

        private void OnEndCreateConection(AnimationControls.AnimNodeControl pDestNode)
        {
            // Add conexion
            AnimControlData animData = _AnimationSystem.GetAnimDataFromControl(pDestNode);
            if (animData != null && animData.AnimNode != null && _iDragAnimItemSource != -1 && _DragControlAnimNodeSource != null && pDestNode != null && _DragControlAnimNodeSource != pDestNode)
            {
                // Si podemos crear el nodo
                _AnimationSystem.XMAnimationSystem.LinkTwoNodes(_DragAnimNodeSource, _iDragAnimItemSource, animData.AnimNode);
                _bNeedToAskConfirmation = true;
            }

            _iDragAnimItemSource = -1;
            _DragControlAnimNodeSource = null;
            _DragAnimNodeSource        = null;
        }

        private void OnDelteOutComing(AnimationControls.AnimNodeControl pSourceNode, int iIdxChild)
        {
            AnimControlData animData = _AnimationSystem.GetAnimDataFromControl(pSourceNode);
            if (animData != null && animData.AnimNode != null)
            {
                animData.AnimNode.DestroyOutcomeNodeConnection(iIdxChild);
                _bNeedToAskConfirmation = true;
            }

        }

        private void OnDelteInComing(AnimationControls.AnimNodeControl pSourceNode)
        {
            AnimControlData animData = _AnimationSystem.GetAnimDataFromControl(pSourceNode);
            if (animData != null && animData.AnimNode != null)
            {
                animData.AnimNode.DestroyIncomeNodeConnections();
                _bNeedToAskConfirmation = true;
            }
        }

        private void OnItemNodeMouseDown(AnimationControls.AnimNodeControl pSourceControl, int iIdxChild, System.Drawing.Point ControlPosition)
        {
            AnimControlData animData = _AnimationSystem.GetAnimDataFromControl(pSourceControl);
            if (animData != null && animData.AnimNode != null && !animData.AnimNode.FixedChildren && iIdxChild >= 0 && iIdxChild <animData.AnimNode.ItemList.Count)
            {
                _MenuAnimDataSource  = animData;
                _iMenuNodeItemSource = iIdxChild;
                // Show menu
                contextMenuItemNodes.Show(splitContainer1.Panel2, ControlPosition);
            }
        }

        private void OnAnimNodeClickCaption(AnimationControls.AnimNodeControl pSourceControl, MouseEventArgs e)
        {
            // If was moving ignore
            if (_bWasMovingNode)
            {
                _bWasMovingNode = false;
                return;
            }

            // Looking for sourcenode
            AnimControlData animData = _AnimationSystem.GetAnimDataFromControl(pSourceControl);
            if (animData != null && animData.AnimNode != null)
            {                             
                // A few different actions 
                if (e.Button == MouseButtons.Left)
                {
                    // Control Key add to selected list
                    if ((Control.ModifierKeys & Keys.Control) != Keys.Control)
                        ClearSelectedNodes();

                    // Check if it selected to unselect
                    if (_SelectedNodes.Contains(animData))
                    {
                        _SelectedNodes.Remove(animData);
                        animData.AnimControl.CaptionColor = System.Drawing.Color.Black;
                        if (propertyGrid1.SelectedObject == animData.AnimNode)
                            propertyGrid1.SelectedObject = null;
                    }
                    else
                    {
                        // Add to selected
                        animData.AnimControl.CaptionColor = System.Drawing.Color.Yellow;
                        _SelectedNodes.Add(animData);

                        // And properties in grid too
                        propertyGrid1.SelectedObject = animData.AnimNode;
                        propertyGrid1.Refresh();
                        animData.AnimControl.BringToFront();
                    }
                }
                else if (e.Button == MouseButtons.Right)
                {
                    // Show menu
                    _MenuAnimDataSource = animData;
                    System.Drawing.Point pPoint = new System.Drawing.Point(pSourceControl.Location.X + e.Location.X,
                        pSourceControl.Location.Y + e.Location.Y);
                    contextMenuNode.Show(splitContainer1.Panel2, pPoint);
                }
            }
        }


        #endregion


        # region Anim Node Creation

        private void OnCreateGraphicalControl(AnimControlData AnimData)
        {
            AnimData.AnimControl.OnAnimNodeSelected += onClickAnimNode;
            AnimData.AnimControl.OnAnimNodeMoves += OnAnimNodeMove;
            AnimData.AnimControl.OnBeginCreateConection += OnBeginCreateConection;
            AnimData.AnimControl.OnEndCreateConection += OnEndCreateConection;
            AnimData.AnimControl.OnDelteInComing += OnDelteInComing;
            AnimData.AnimControl.OnDelteOutComing += OnDelteOutComing;
            AnimData.AnimControl.OnItemNodeMouseDown += OnItemNodeMouseDown;
            AnimData.AnimControl.DragOver += onDragOver;
            AnimData.AnimControl.OnClickCaption += OnAnimNodeClickCaption;
            _bNeedToAskConfirmation = true;
        }

        private void onClickOnPanel(object sender, MouseEventArgs e)
        {
            // save the point and show popup (and not showing node)
            if (e.Button == MouseButtons.Right && _MenuAnimDataSource == null)
            {
                _MenuPoint = new System.Drawing.Point(e.X, e.Y);
                contextMenuAddNodes.Show(splitContainer1.Panel2, _MenuPoint);
            }
            if (e.Button == MouseButtons.Left)
            {
                // Begin box selection or deselect
                if ((Control.ModifierKeys & Keys.Control) == Keys.Control && _DragControlAnimNodeSource == null)
                {
                    _DragBeginPoint = new System.Drawing.Point(e.X, e.Y);
                    _bBoxSelecting = true;
                }
                else
                {
                    // Deselect all
                    ClearSelectedNodes();
                    _MenuAnimDataSource = null;
                }
            }
        }

        private void onReleaseOnPanel(object sender, MouseEventArgs e)
        {
            // Check selected by box
            if (_bBoxSelecting)
            {
                // Select all nodes inside
                _AnimationSystem.SelectControlsInRectangle(GetCorrectRectangle(_DragBeginPoint,_MovePanelPoint) , _SelectedNodes);
                _bBoxSelecting = false;
            }
        }

        private void addAnimNodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem ItemStrip = (ToolStripMenuItem)sender;
            AnimControlData AnimData = _AnimationSystem.AddNode(_MenuPoint, (string)ItemStrip.Tag, true);
            if (AnimData != null)    
                AnimData.AnimControl.BringToFront();
        }

        #endregion


        #region Item menu

        private void addNodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_MenuAnimDataSource != null && _MenuAnimDataSource.AnimNode != null)
            {
                _MenuAnimDataSource.AnimNode.AddChild("Element " + _MenuAnimDataSource.AnimNode.ItemList.Count, 0);
                _AnimationSystem.RecreateControl(_MenuAnimDataSource);
            }
            _MenuAnimDataSource = null;
            _iMenuNodeItemSource = -1;
            _bNeedToAskConfirmation = true;
        }

        private void delteChildToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_MenuAnimDataSource != null && _MenuAnimDataSource.AnimNode != null)
            {
                _MenuAnimDataSource.AnimNode.RemoveChild(_iMenuNodeItemSource);
                _AnimationSystem.RecreateControl(_MenuAnimDataSource);
            }
            _iMenuNodeItemSource = -1;
            _MenuAnimDataSource = null;
            _bNeedToAskConfirmation = true;
        }

        private void renameChildToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_MenuAnimDataSource != null && _MenuAnimDataSource.AnimNode != null)
            {
                if (_iMenuNodeItemSource >= 0 && _iMenuNodeItemSource < _MenuAnimDataSource.AnimNode.ItemList.Count)
                {
                    AnimationNodeItem item = _MenuAnimDataSource.AnimNode.ItemList[_iMenuNodeItemSource];
                    frmInput inputForm = new frmInput(item);
                    inputForm.ShowDialog(splitContainer1.Panel2);
                    _AnimationSystem.RecreateControl(_MenuAnimDataSource);
                }
            }
            _iMenuNodeItemSource = -1;
            _MenuAnimDataSource = null;
            _bNeedToAskConfirmation = true;
        }

        private void contextMenuStrip2_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            if (e.CloseReason != ToolStripDropDownCloseReason.ItemClicked)
            {
                _iMenuNodeItemSource = -1;
                _MenuAnimDataSource = null;
            }
            _DisableNextPanelMove = true;            
        }

        #endregion


        # region Node menu

        private void onDeleteNode(object sender, EventArgs e)
        {
            // If item is in selected list delete all, otherwise delete only node
            if (_MenuAnimDataSource != null && !_SelectedNodes.Contains(_MenuAnimDataSource))
            {
                if (propertyGrid1.SelectedObject != null && propertyGrid1.SelectedObject == _MenuAnimDataSource.AnimNode)
                    propertyGrid1.SelectedObject = null;
                _AnimationSystem.DeleteNode(_MenuAnimDataSource);
                _bNeedToAskConfirmation = true;
            }
            else
            {
                // Delete all selected    
                foreach (AnimControlData animData in _SelectedNodes)
                {
                    // Check if selected
                    if (propertyGrid1.SelectedObject != null && propertyGrid1.SelectedObject == animData.AnimNode)
                        propertyGrid1.SelectedObject = null;
                    if (_MenuAnimDataSource == animData)
                        _MenuAnimDataSource = null;
                    _AnimationSystem.DeleteNode(animData);
                    _bNeedToAskConfirmation = true;
                }
                _SelectedNodes.Clear();
            }
        }

        private void cloneNodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Clear selection
            foreach (AnimControlData selectNode in _SelectedNodes)
                selectNode.AnimControl.CaptionColor = System.Drawing.Color.Black;
            
            // Clone
            _AnimationSystem.CloneNodes(_SelectedNodes);

            // Change color
            foreach (AnimControlData selectNode in _SelectedNodes)
                selectNode.AnimControl.CaptionColor = System.Drawing.Color.Yellow;

            _MenuAnimDataSource = null;
        }

        private void cloneBranchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_MenuAnimDataSource != null)
            {
                 // Clear selection
                foreach (AnimControlData selectNode in _SelectedNodes)
                    selectNode.AnimControl.CaptionColor = System.Drawing.Color.Black;
                _SelectedNodes.Clear();

                // Clone a get result
                _AnimationSystem.CloneBranch(_MenuAnimDataSource, _SelectedNodes);
                
                // Change color
                foreach (AnimControlData selectNode in _SelectedNodes)
                    selectNode.AnimControl.CaptionColor = System.Drawing.Color.Yellow;

                _MenuAnimDataSource = null;
            }
        }

        private void deleteBranchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_MenuAnimDataSource != null)
            {
                // Clear selection
                foreach (AnimControlData selectNode in _SelectedNodes)
                    selectNode.AnimControl.CaptionColor = System.Drawing.Color.Black;
                _SelectedNodes.Clear();
                propertyGrid1.SelectedObject = null;

                // Delete branch
                _AnimationSystem.DeleteBranch(_MenuAnimDataSource);
                _MenuAnimDataSource = null;
            }
        }

        #endregion


        #region Menu Handlers


        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AskForConfirmation())
            {
                ClearCachedNode();
                _AnimationSystem.NewFile();
                _bNeedToAskConfirmation = false;
            }
            XNAAnimationEditor.StaticXNAAnimationEditor.RecacheShader();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Save            
            saveFileDialog1.InitialDirectory = ".\\Content";
            saveFileDialog1.FileName = "AnimGraph.xmas";
            saveFileDialog1.Filter = "XMas files (*.xmas)|*.xmas";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                _AnimationSystem.SaveToFile(saveFileDialog1.FileName);
                _bNeedToAskConfirmation = false;
            }
            XNAAnimationEditor.StaticXNAAnimationEditor.RecacheShader();
        }

        private void abrirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AskForConfirmation())
            {
                openFileDialog1.InitialDirectory = ".\\Content";
                openFileDialog1.Filter = "XMas files (*.xmas)|*.xmas";
                openFileDialog1.FileName = "";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    ClearCachedNode();
                    _AnimationSystem.LoadFromFile(openFileDialog1.FileName);
                    _bNeedToAskConfirmation = false;
                }
                _DisableNextPanelMove = true;
            }
            XNAAnimationEditor.StaticXNAAnimationEditor.RecacheShader();
        }

        private void importNewModelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = ".\\Content";
            //openFileDialog1.Filter = "Model files (*.fbx;*.x)|*.fbx;*.x";
            // TODO: Mejorar esto con plugines
            openFileDialog1.Filter = "All Supported|*.csf;*.xnb;*.fbx|Cal3D files (*.csf)|*.csf|FBX files (*.fbx)|*.fbx|Compiled (*.xnb)|*.xnb";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                _AnimationSystem.ImportModel(openFileDialog1.FileName);
            XNAAnimationEditor.StaticXNAAnimationEditor.RecacheShader();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox frmAbout = new AboutBox();
            frmAbout.ShowDialog(this);
        }


        private void onMainMenuClosed(object sender, EventArgs e)
        {
            _DisableNextPanelMove = true;
        }

        #endregion


        # region Buttons Handlers

        private void toolStripButtonScaleMinus_Click(object sender, EventArgs e)
        {
            _AnimationSystem.ScaleControls(false);
        }

        private void toolStripButtonScalePlus_Click(object sender, EventArgs e)
        {
            _AnimationSystem.ScaleControls(true);
        }

        private void toolStripButtonReset_Click(object sender, EventArgs e)
        {
            _AnimationSystem.ResetView();
        }

        #endregion


       
    }
}